<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8" />
  <title>Hello World</title>
  <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>

  <!-- Don't use this in production: -->
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>

<body>
  <div id="root"></div>

  <script type="text/babel">

    const { useReducer } = React;
    /* 
      把操作状态数据的代码进行整理
      state 代表操作之前的，原来的值
      action = { type:具体的操作名称，payload:操作附带的具体值 }

      组件
        状态数据
        操作状态数据的方法
      使用
        状态数据
    */
    function useCount() {
      function reducer(state, action) {
        switch (action.type) {
          case 'inc':
            return {
              ...state,  // 保留原有的 staAte 属性
              count: state.count + action.payload  // 只更新 count 属性
            }
          case 'dec':
            return {
              ...state,  // 保留原有的 state 属性
              count: state.count - action.payload  // 只更新 count 属性
            }
          case 'rename':
            return {
              ...state,  // 保留原有的 state 属性
              name: action.payload  // 只更新 name 属性
            }
          default:
            return state
        }
      }

      return useReducer(reducer, { name: '青苹果', count: 100 })
    }

    function MyApp() {
      // const [count, setCount] = useState(0)
      const [fruit, dispatch] = useCount()

      return <>
        <h1> {fruit.count} </h1>
        <button onClick={() => dispatch({ type: 'inc', payload: 1 })}>加</button>
        <button onClick={() => dispatch({ type: 'dec', payload: 1 })}>减</button>
        <button onClick={() => dispatch({ type: 'rename', payload: '黄元帅' })}>改名</button>
      </>
    }

    // 浏览器DOM对象
    const container = document.getElementById('root');
    // 浏览器DOM对象转换成reactDOM对象
    const root = ReactDOM.createRoot(container);
    root.render(<MyApp />);

    console.log(root);

  </script>

</body>

</html>